'''
Various content providers for apkn.resource
'''
from zope.interface import Interface, implements
from zope.component import adapts
from zope.contentprovider.interfaces import IContentProvider
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.app.pagetemplate import ViewPageTemplateFile
from Acquisition import aq_inner

from Products.CMFCore.utils import getToolByName

from apkn.resource.interfaces import IResource, IResourceFolder
from apkn.resource.config import RESOURCECOUNTRIES

from plone.memoize.instance import memoize

RECENT_ITEM_COUNT = 10

class RecentResourcesListing(object):
        '''
        Return a listing of a resource folder
        '''
        implements(IContentProvider)
        adapts(Interface, IDefaultBrowserLayer)

        def __init__(self, context, request, view):
                self.context = context
                self.request = request
                self.__parent = view

        def update(self):
                pass

        def getSearchPath(self):
                search_path = None
                current_object = aq_inner(self.context)
                if IResourceFolder.providedBy(current_object):
                        search_path = '/'.join(current_object.getPhysicalPath())
                return search_path

        def getRecentItems(self):
                recent_items = []

                catalog = getToolByName(self.context, 'portal_catalog')
                if catalog:
                        search_path = self.getSearchPath()
                        if search_path:
                                q_path = {'query': search_path, 'depth': 1}
                                catalog_items = catalog.searchResults(path = q_path,
                                                                      review_state = 'published',
                                                                      sort_on = 'Date',
                                                                      sort_limit = RECENT_ITEM_COUNT,
                                                                      object_provides = \
                                                                      IResource.__identifier__,
                                                                      )
                                recent_items = [c_item.getObject() for c_item in catalog_items]
                return recent_items

        render = ViewPageTemplateFile("templates/recent_resources.pt")


class ResourcesCountryListing(object):
        '''
        Return a listing of a resource folder
        '''
        implements(IContentProvider)
        adapts(Interface, IDefaultBrowserLayer)

        def __init__(self, context, request, view):
                self.context = context
                self.request = request
                self.__parent = view

        def update(self):
                pass

        def getSearchPath(self):
                search_path = None
                current_object = aq_inner(self.context)
                if IResourceFolder.providedBy(current_object):
                        search_path = '/'.join(current_object.getPhysicalPath())
                return search_path

        @memoize
        def getCountryListing(self):
            catalog = self.context.portal_catalog
            resource_path = '/'.join(self.context.getPhysicalPath())
            catalog_query = {
                'path':dict(query=resource_path, depth=1)
            }
            resources_here = catalog(catalog_query)
            if not resources_here:
                catalog_query['Language'] = ''
                resources_here = catalog(catalog_query)
            resource_countries = [o.getObject().country
                                 for o in resources_here]
            country_uniques = {}
            map(country_uniques.__setitem__,
                resource_countries,
                [])
            country_list_ids = country_uniques.keys()
            country_list = [{u'country_id': country_id,
            u'country_title': RESOURCECOUNTRIES.getValue(country_id)}
            for country_id in country_list_ids]
            country_list = sorted(country_list,
            key = lambda country_data: country_data['country_id'])
            return country_list

        render = ViewPageTemplateFile("templates/resources_country_listing.pt")
